package com.spider.iceCream;

import com.spider.iceCream.entity.DayRank;
import com.spider.iceCream.entity.Video;
import com.spider.iceCream.service.DayRankService;
import com.spider.iceCream.service.VideoService;
import com.spider.iceCream.spiderComponent.UrltoCid;
import com.spider.iceCream.spiderComponent.main.Crawler;
import com.spider.iceCream.spiderComponent.model.Rank;
import com.spider.iceCream.spiderComponent.model.VideoModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author Lord
 * @date 2021/7/13 16:24
 */
@Component
public class Spider {
    @Autowired
    DayRankService dayRankService;
    @Autowired
    VideoService videoService;

    @Scheduled(cron = "0 2 0 * * ?")
    public void webSpider(){
        System.out.println("爬虫启动-"+getDate());
        try {
            int vStatus = 0;
            int rStatus = 0;
            Crawler b = new Crawler();
            List<Rank> rankList = b.getRank();
            for (Rank r :
                    rankList) {
                String category = r.getCategory();
                System.out.println("正在插入类别:"+category);
                for (VideoModel v :
                        r.getRankList()) {
                    UrltoCid urltoCid = new UrltoCid();
                    int cid = urltoCid.urlToCid(v.getVideoUrl());
                    Video video = new Video(v.getOid(),cid,v.getTitle(),v.getVideoUrl(),v.getAuthor().trim(),v.getImgUrl());
                    Video isExists = videoService.isExistVideo(video.getOid());
                    DayRank now = new DayRank(v.getOid(),v.getRank(),category,getDate(),v.getPoint());
                    DayRank isExistRank = dayRankService.isExistRank(now);
                    if (isExists == null){
                        vStatus = videoService.insertVideo(video);
                        rStatus = dayRankService.insertRank(now);
                    }else if(isExistRank == null){
                        videoService.updateImgUrl(isExists);
                        rStatus = dayRankService.insertRank(now);
                    }
                }
            }
        }catch (Exception e){
            System.out.println(e);
            System.out.println("程序异常");
        }
        System.out.println("插入完成-"+getDate());
    }

    public String getDate(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
        simpleDateFormat.applyPattern("yyyy-MM-dd");
        Date date = new Date();
        return simpleDateFormat.format(date);
    }
}